package team.szm.scd.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import team.szm.scd.database.dto.RequestWrapper;
import team.szm.scd.database.dto.Result;
import team.szm.scd.database.entity.Doctor;
import team.szm.scd.database.entity.Register;
import team.szm.scd.database.entity.User;
import team.szm.scd.database.vo.RegisterRemainVO;
import team.szm.scd.database.vo.RegisterVO;
import team.szm.scd.service.interfaces.ILoginService;
import team.szm.scd.service.interfaces.IRegisterService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/register")
@Slf4j
public class RegisterController {
    @Resource
    IRegisterService registerService;
    @Resource
    ILoginService loginService;

    @PostMapping("/all")
    @ResponseBody
    public Result<List<RegisterRemainVO>>
    getAllRegisterInfo(@RequestParam Integer hospitalId, @RequestParam Integer departmentId, HttpSession session) {
        if (loginService.noUserAndNoDoctorLogin(session)) {
            return Result.needLogin();
        }
        LocalDate today = LocalDate.now();
        return Result.success(registerService.registerRemainInfo(hospitalId, departmentId, today));
    }

    @PostMapping("/add")
    @ResponseBody
    public Result<Boolean> addRegister(@RequestBody Register register, HttpSession session) {
        if (loginService.noUserAndNoDoctorLogin(session)) {
            return Result.needLogin();
        }
        log.trace("add register: " + register);
        if (registerService.addRegister(register, LocalDateTime.now())) {
            return Result.success(true);
        }
        return Result.fail(false);
    }

    @PostMapping("/user_info")
    @ResponseBody
    public Result<List<RegisterVO>> userRegisterInfo
            (@RequestBody RequestWrapper<Integer> hospitalId, HttpSession session) {
        User user = loginService.getLoginUser(session);
        if (user != null) {
            return Result.success(registerService.userRegisterInfo(user.getId(), hospitalId.value));
        }
        return Result.needLogin();
    }

    @GetMapping("/doctor_have")
    @ResponseBody
    public Result<List<RegisterVO>> registersDoctorHave(HttpSession session) {
        Doctor doctor = loginService.getLoginDoctor(session);
        if (doctor == null) {
            return Result.needLogin();
        }
        return Result.success(registerService.registersDoctorHave(doctor.getId(), LocalDate.now()));
    }
}
